<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Auth_controller extends MX_Controller {

    function __construct() {
        parent::__construct();

        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->library('tank_auth');
        $this->lang->load('tank_auth', 'pt-BR');
    }

    function index() {
        redirect('/cms/');
    }

    /**
     * Login user on the site
     *
     * @return void
     */
    function login() {
        $v_dados = array();
        /// OTIMIZAR
        $v_dados['cod'] = '111';
        $v_dados['msg'] = '';
        /// FIM OTIMIZAR
        if ($this->tank_auth->is_logged_in()) {         // logged in
            $v_dados['cod'] = '999';
            $v_dados['msg'] = 'Aguarde redirecionando.';
        } elseif ($this->tank_auth->is_logged_in(FALSE)) {      // logged in, not activated
            $v_dados['cod'] = '111';
            $v_dados['msg'] = 'Login inválido.';
        } else {
            $v_dados['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND $this->config->item('use_username', 'tank_auth'));
            $v_dados['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');

            $this->form_validation->set_rules('username', 'Login', 'trim|required|xss_clean');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');
            $this->form_validation->set_rules('remember', 'Remember me', 'integer');

            // Get login for counting attempts to login
            if ($this->config->item('login_count_attempts', 'tank_auth') AND ($login = $this->input->post('login'))) {
                $login = $this->input->xss_clean($login);
            } else {
                $login = '';
            }

            //$v_dados['use_recaptcha'] = $this->config->item('use_recaptcha', 'tank_auth');
            if ($this->tank_auth->is_max_login_attempts_exceeded($login)) {
                /* if ($v_dados['use_recaptcha'])
                  $this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
                  else */
                $this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
            }
            if ($this->form_validation->run() === FALSE) {        // validation ok
                $v_dados['cod'] = '111';
                $v_dados['msg'] = $this->form_validation->error_string_simples();
            } else {
                if ($this->tank_auth->login($this->form_validation->set_value('username'), $this->form_validation->set_value('password'), $this->form_validation->set_value('remember'), $v_dados['login_by_username'], $v_dados['login_by_email'])) {        // success
                    $v_dados['cod'] = '999';
                    $v_dados['msg'] = 'Aguarde redirecionando.';
                } else {
                    $errors = $this->tank_auth->get_error_message();
                    if (isset($errors['banned'])) {        // banned user
                        $v_dados['cod'] = '111';
                        $v_dados['msg'] = $this->lang->line('auth_message_banned') . ' ' . $errors['banned'];
                    } elseif (isset($errors['not_activated'])) {    // not activated user
                        $v_dados['cod'] = '111';
                        $v_dados['msg'] = 'Usuário não está ativo.';
                    } else {             // fail
                        $v_dados['cod'] = '111';
                        foreach ($errors as $k => $v)
                            $v_dados['msg'] .= '<br />' . $this->lang->line($v);
                    }
                }
            }
        }
        echo json_encode($v_dados);
    }

    /**
     * Logout user
     *
     * @return void
     */
    function logout() {
        $this->tank_auth->logout();

        //$this->_show_message($this->lang->line('auth_message_logged_out'));
        redirect(base_cms());
    }

    /**
     * Register user on the site
     *
     * @return void

      /// ANTIGO REGISTER
      function register()
      {
      if ($this->tank_auth->is_logged_in()) {									// logged in
      redirect('');

      } elseif ($this->tank_auth->is_logged_in(FALSE)) {						// logged in, not activated
      redirect('/auth/send_again/');

      } elseif (!$this->config->item('allow_registration', 'tank_auth')) {	// registration is off
      $this->_show_message($this->lang->line('auth_message_registration_disabled'));
      return;

      } else {
      $use_username = $this->config->item('use_username', 'tank_auth');
      if ($use_username) {
      $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length['.$this->config->item('username_min_length', 'tank_auth').']|max_length['.$this->config->item('username_max_length', 'tank_auth').']|alpha_dash');
      }
      $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
      $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length['.$this->config->item('password_min_length', 'tank_auth').']|max_length['.$this->config->item('password_max_length', 'tank_auth').']|alpha_dash');
      $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');

      $captcha_registration	= $this->config->item('captcha_registration', 'tank_auth');
      $use_recaptcha			= $this->config->item('use_recaptcha', 'tank_auth');
      if ($captcha_registration) {
      if ($use_recaptcha) {
      $this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
      } else {
      $this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
      }
      }
      $data['errors'] = array();

      $email_activation = $this->config->item('email_activation', 'tank_auth');

      if ($this->form_validation->run()) {								// validation ok
      if (!is_null($data = $this->tank_auth->create_user(
      $use_username ? $this->form_validation->set_value('username') : '',
      $this->form_validation->set_value('email'),
      $this->form_validation->set_value('password'),
      $email_activation))) {									// success

      $data['site_name'] = $this->config->item('website_name', 'tank_auth');

      if ($email_activation) {									// send "activate" email
      $data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;

      $this->_send_email('activate', $data['email'], $data);

      unset($data['password']); // Clear password (just for any case)

      $this->_show_message($this->lang->line('auth_message_registration_completed_1'));
      return;

      } else {
      if ($this->config->item('email_account_details', 'tank_auth')) {	// send "welcome" email

      $this->_send_email('welcome', $data['email'], $data);
      }
      unset($data['password']); // Clear password (just for any case)

      $this->_show_message($this->lang->line('auth_message_registration_completed_2').' '.anchor('/auth/login/', 'Login'));
      return;
      }
      } else {
      $errors = $this->tank_auth->get_error_message();
      foreach ($errors as $k => $v)	$data['errors'][$k] = $this->lang->line($v);
      }
      }
      if ($captcha_registration) {
      if ($use_recaptcha) {
      $data['recaptcha_html'] = $this->_create_recaptcha();
      } else {
      $data['captcha_html'] = $this->_create_captcha();
      }
      }
      $data['use_username'] = $use_username;
      $data['captcha_registration'] = $captcha_registration;
      $data['use_recaptcha'] = $use_recaptcha;
      $this->load->view('auth/register_form', $data);
      }
      }
     */
    function register() {
        if (!$this->tank_auth->is_logged_in()) {         // logged in
            redirect('');
        } elseif ($this->tank_auth->is_logged_in(FALSE)) {      // logged in, not activated
            redirect('/auth/send_again/');
        } elseif (!$this->config->item('allow_registration', 'tank_auth')) { // registration is off
            $this->_show_message($this->lang->line('auth_message_registration_disabled'));
            return;
        } else {
            $use_username = $this->config->item('use_username', 'tank_auth');
            if ($use_username) {
                $this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean|min_length[' . $this->config->item('username_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('username_max_length', 'tank_auth') . ']|alpha_dash');
            } else {
                $usuario = explode('@', $this->input->post('email'));
            }
            $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');
            $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|min_length[' . $this->config->item('password_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('password_max_length', 'tank_auth') . ']|alpha_dash');
            $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|xss_clean|matches[password]');

            $captcha_registration = $this->config->item('captcha_registration', 'tank_auth');
            $use_recaptcha = $this->config->item('use_recaptcha', 'tank_auth');
            if ($captcha_registration) {
                if ($use_recaptcha) {
                    $this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|xss_clean|required|callback__check_recaptcha');
                } else {
                    $this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|xss_clean|required|callback__check_captcha');
                }
            }
            $data['errors'] = array();

            $email_activation = $this->config->item('email_activation', 'tank_auth');

            if ($this->form_validation->run()) {        // validation ok
                if (!is_null($data = $this->tank_auth->create_user(
                                //$use_username ? $this->form_validation->set_value('username') : '',
                                $use_username ? $this->form_validation->set_value('username') : $usuario[0], $this->form_validation->set_value('email'), $this->form_validation->set_value('password'), $email_activation))) {         // success
                    $data['site_name'] = $this->config->item('website_name', 'tank_auth');

                    if ($email_activation) {         // send "activate" email
                        $data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;

                        $this->_send_email('activate', $data['email'], $data);

                        unset($data['password']); // Clear password (just for any case)

                        $this->_show_message($this->lang->line('auth_message_registration_completed_1'));
                        return;
                    } else {
                        if ($this->config->item('email_account_details', 'tank_auth')) { // send "welcome" email
                            $this->_send_email('welcome', $data['email'], $data);
                        }
                        unset($data['password']); // Clear password (just for any case)
                        //$this->_show_message($this->lang->line('auth_message_registration_completed_2').' '.anchor('/auth/login/', 'Login'));
                        redirect('/' . base_cms() . 'usuario');
                        return;
                    }
                } else {
                    $errors = $this->tank_auth->get_error_message();
                    foreach ($errors as $k => $v)
                        $data['errors'][$k] = $this->lang->line($v);
                }
            }
            if ($captcha_registration) {
                if ($use_recaptcha) {
                    $data['recaptcha_html'] = $this->_create_recaptcha();
                } else {
                    $data['captcha_html'] = $this->_create_captcha();
                }
            }
            $data['use_username'] = $use_username;
            $data['captcha_registration'] = $captcha_registration;
            $data['use_recaptcha'] = $use_recaptcha;
            //$this->load->view('auth/register_form', $data);
            redirect('/' . base_cms() . 'usuario/novo');
        }
    }

    /**
     * Send activation email again, to the same or new email address
     *
     * @return void
     */
    function send_again() {
        if (!$this->tank_auth->is_logged_in(FALSE)) {       // not logged in or activated
            redirect('/auth/login/');
        } else {
            $this->form_validation->set_rules('email', 'Email', 'trim|required|xss_clean|valid_email');

            $data['errors'] = array();

            if ($this->form_validation->run()) {        // validation ok
                if (!is_null($data = $this->tank_auth->change_email(
                                $this->form_validation->set_value('email')))) {   // success
                    $data['site_name'] = $this->config->item('website_name', 'tank_auth');
                    $data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;

                    $this->_send_email('activate', $data['email'], $data);

                    $this->_show_message(sprintf($this->lang->line('auth_message_activation_email_sent'), $data['email']));
                    return;
                } else {
                    $errors = $this->tank_auth->get_error_message();
                    foreach ($errors as $k => $v)
                        $data['errors'][$k] = $this->lang->line($v);
                }
            }
            $this->load->view('auth/send_again_form', $data);
        }
    }

    /**
     * Activate user account.
     * User is verified by user_id and authentication code in the URL.
     * Can be called by clicking on link in mail.
     *
     * @return void
     */
    function activate() {
        $user_id = $this->uri->segment(3);
        $new_email_key = $this->uri->segment(4);

        // Activate user
        if ($this->tank_auth->activate_user($user_id, $new_email_key)) {  // success
            $this->tank_auth->logout();
            $this->_show_message($this->lang->line('auth_message_activation_completed') . ' ' . anchor('/auth/login/', 'Login'));
        } else {                // fail
            $this->_show_message($this->lang->line('auth_message_activation_failed'));
        }
    }

    /**
     * Generate reset code (to change password) and send it to user
     *
     * @return void
     */
    function forgot_password() {
        if ($this->tank_auth->is_logged_in()) {         // logged in
//pre('aaaa');            
            redirect(base_cms());
        } elseif ($this->tank_auth->is_logged_in(FALSE)) {      // logged in, not activated
//pre('bbbb');            
            redirect(base_cms() . '/auth/send_again/');
        } else {
            //$this->form_validation->set_rules('login', 'Email or login', 'trim|required|xss_clean');
            $this->form_validation->set_rules('email', 'E-mail', 'trim|required|valid_email|xss_clean');

            $v_dados = array();
            $v_dados['errors'] = "";
            $v_dados['sucesso'] = "";

            if ($this->form_validation->run() === FALSE) {
                $v_dados['errors'] = $this->form_validation->error_string_simples(); // validation ok
            } else {
                $data = $this->tank_auth->forgot_password($this->form_validation->set_value('email'));
                if (!is_null($data)) {
                    $data['site_name'] = $this->config->item('website_name', 'tank_auth');
                    $v_dados['sucesso'] = $this->_send_email('forgot_password', $this->form_validation->set_value('email'), $data);
                } else {

                    $errors = $this->tank_auth->get_error_message();
                    if (count($errors) > 0) {
                        foreach ($errors as $k => $v) {
                            $v_dados['errors'] .= $this->lang->line($v);
                        }
                    }
                }
            }
            $this->lang->load('login_esqueci_senha_view');
            $v_dados['email'] = $this->lang->line('login_email');
            $v_dados['submit'] = $this->lang->line('login_submit');
            $this->parser->parse_cms('login_esqueci_senha_view', $v_dados);
        }
    }

    /**
     * Replace user password (forgotten) with a new one (set by user).
     * User is verified by user_id and authentication code in the URL.
     * Can be called by clicking on link in mail.
     *
     * @return void
     */
    function reset_password($user_id, $new_pass_key) {
        //$user_id		= $this->uri->segment(3);
        //$new_pass_key	= $this->uri->segment(4);

        $this->form_validation->set_rules('nova_senha', 'Nova Senha', 'trim|required|xss_clean|min_length[' . $this->config->item('password_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('password_max_length', 'tank_auth') . ']|alpha_dash');
        $this->form_validation->set_rules('confirma_nova_senha', 'Confirmar Nova Senha', 'trim|required|xss_clean|matches[nova_senha]');

        $v_dados['errors'] = array();
        if ($this->form_validation->run() != FALSE) {
            $dados = $this->tank_auth->reset_password($user_id, $new_pass_key, $this->form_validation->set_value('nova_senha')); // validation ok
            //$dados = $this->tank_auth->reset_password(21,"98b04d6df1e3668be0155efdc344a8eb","acesso"); // validation ok
            if (!is_null($dados)) { // success
                $v_dados['site_name'] = $this->config->item('website_name', 'tank_auth');

                // Send email with new password
                $this->_send_email('reset_password', $dados['email'], $dados);

                $this->_show_message($this->lang->line('auth_message_new_password_activated') . ' ' . anchor(base_cms(), 'Login'), 'Resetar e-mail');
                return;
            } else {              // fail
                $this->_show_message($this->lang->line('auth_message_new_password_failed') . ' ' . anchor(base_cms(), 'Página Inicial'), 'Resetar e-mail');
                return;
            }
        } else {
            // Try to activate user by password key (if not activated yet)
            //if ($this->config->item('email_activation', 'tank_auth')) {
            if ($this->tank_auth->activate_user($user_id, $new_pass_key, FALSE)) {
                $this->_show_message($this->lang->line('auth_message_new_password_activated') . ' ' . anchor(base_cms(), 'Página Inicial'), 'Resetar e-mail');
                return;
            }
            //redirect(base_cms());
            //}

            if (!$this->tank_auth->can_reset_password($user_id, $new_pass_key)) {
                $this->_show_message($this->lang->line('auth_message_new_password_failed') . ' ' . anchor(base_cms(), 'Página Inicial'), 'Resetar e-mail');
                return;
            }
        }
        //$this->load->view('auth/reset_password_form', $data);
        $this->lang->load('login_ressetar_senha_view');
        $v_dados['uri_string'] = $this->uri->uri_string();
        $v_dados['nova_senha'] = $this->lang->line('login_nova_senha');
        $v_dados['confirma_nova_senha'] = $this->lang->line('login_confirma_nova_senha');
        $v_dados['login'] = $this->lang->line('login_login');
        $v_dados['titulo_login'] = $this->lang->line('login_titulo_login');
        //pre($v_dados);
        $this->parser->parse_cms('login_ressetar_senha_view', $v_dados);
    }

    /**
     * Change user password
     *
     * @return void
     */
    function change_password() {
        if (!$this->tank_auth->is_logged_in()) {        // not logged in or not activated
            redirect('/auth/login/');
        } else {
            $this->form_validation->set_rules('old_password', 'Senha Antiga', 'trim|required|xss_clean');
            $this->form_validation->set_rules('new_password', 'Nova Senha', 'trim|required|xss_clean|min_length[' . $this->config->item('password_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('password_max_length', 'tank_auth') . ']|alpha_dash');
            $this->form_validation->set_rules('confirm_new_password', 'Confirmar nova Senha', 'trim|required|xss_clean|matches[new_password]');

            $data['errors'] = array();

            if ($this->form_validation->run()) {        // validation ok
                if ($this->tank_auth->change_password(
                                $this->form_validation->set_value('old_password'), $this->form_validation->set_value('new_password'))) { // success
                    $this->_show_message($this->lang->line('auth_message_password_changed'));
                    return;
                } else {              // fail
                    $errors = $this->tank_auth->get_error_message();
                    foreach ($errors as $k => $v)
                        $data['errors'][$k] = $this->lang->line($v);
                }
            }
            //$this->load->view('auth/change_password_form', $data);
            redirect('/' . base_cms() . 'usuario');
        }
    }

    /**
     * Change user email
     *
     * @return void
     */
    function change_email() {
        if (!$this->tank_auth->is_logged_in()) {        // not logged in or not activated
            redirect('/auth/login/');
        } else {
            $this->form_validation->set_rules('password', 'Senha', 'trim|required|xss_clean');
            $this->form_validation->set_rules('email', 'E-mail', 'trim|required|xss_clean|valid_email');

            $data['errors'] = array();

            if ($this->form_validation->run()) {        // validation ok
                if (!is_null($data = $this->tank_auth->set_new_email(
                                $this->form_validation->set_value('email'), $this->form_validation->set_value('password')))) {   // success
                    $data['site_name'] = $this->config->item('website_name', 'tank_auth');

                    // Send email with new email address and its activation link
                    $this->_send_email('change_email', $data['new_email'], $data);

                    $this->_show_message(sprintf($this->lang->line('auth_message_new_email_sent'), $data['new_email']));
                    return;
                } else {
                    $errors = $this->tank_auth->get_error_message();
                    foreach ($errors as $k => $v)
                        $data['errors'][$k] = $this->lang->line($v);
                }
            }
            $this->load->view('auth/change_email_form', $data);
        }
    }

    /**
     * Replace user email with a new one.
     * User is verified by user_id and authentication code in the URL.
     * Can be called by clicking on link in mail.
     *
     * @return void
     */
    function reset_email() {
        $user_id = $this->uri->segment(3);
        $new_email_key = $this->uri->segment(4);

        // Reset email
        if ($this->tank_auth->activate_new_email($user_id, $new_email_key)) { // success
            $this->tank_auth->logout();
            $this->_show_message($this->lang->line('auth_message_new_email_activated') . ' ' . anchor('/auth/login/', 'Login'));
        } else {                // fail
            $this->_show_message($this->lang->line('auth_message_new_email_failed'));
        }
    }

    /**
     * Delete user from the site (only when user is logged in)
     *
     * @return void
     */
    function unregister() {
        if (!$this->tank_auth->is_logged_in()) {        // not logged in or not activated
            redirect('/auth/login/');
        } else {
            $this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean');

            $data['errors'] = array();

            if ($this->form_validation->run()) {        // validation ok
                if ($this->tank_auth->delete_user(
                                $this->form_validation->set_value('password'))) {  // success
                    $this->_show_message($this->lang->line('auth_message_unregistered'));
                    return;
                } else {              // fail
                    $errors = $this->tank_auth->get_error_message();
                    foreach ($errors as $k => $v)
                        $data['errors'][$k] = $this->lang->line($v);
                }
            }
            $this->load->view('auth/unregister_form', $data);
        }
    }

    /**
     * Show info message
     *
     * @param	string
     * @return	void
     */
    function _show_message($message, $heading = "Login") {
        $this->parser->parse_cms('erros/general_message', array('heading' => $heading, 'message' => $message));
    }

    /**
     * Send email message of given type (activate, forgot_password, etc.)
     *
     * @param	string
     * @param	string
     * @param	array
     * @return	void
     */
    function _send_email($type, $email, &$data) {
        $config['protocol'] = $this->config->item('protocol');
        $config['smtp_host'] = $this->config->item('smtp_host');
        $config['smtp_user'] = $this->config->item('smtp_user');
        $config['smtp_pass'] = $this->config->item('smtp_pass');
        $config['charset'] = $this->config->item('charset');
        $config['wordwrap'] = $this->config->item('wordwrap');
        $this->load->library('email', $config);
        $this->email->from($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
        $this->email->reply_to($this->config->item('webmaster_email', 'tank_auth'), $this->config->item('website_name', 'tank_auth'));
        $this->email->to($email);
        $this->email->subject(sprintf($this->lang->line('auth_subject_' . $type), $this->config->item('website_name', 'tank_auth')));
        $this->email->message($this->parser->parse_cms('email/' . $type . '-html', $data, TRUE));
        $this->email->set_alt_message($this->parser->parse_cms('email/' . $type . '-txt', $data, TRUE));
        if ($this->email->send()) {
            return sprintf($this->lang->line("auth_message_activation_email_sent"), $email);
        } else {
            return $this->lang->line("auth_message_activation_email_failed");
        }
    }

    /**
     * Create CAPTCHA image to verify user as a human
     *
     * @return	string
     */
    function _create_captcha() {
        $this->load->plugin('captcha');

        $cap = create_captcha(array(
            'img_path' => './' . $this->config->item('captcha_path', 'tank_auth'),
            'img_url' => base_url() . $this->config->item('captcha_path', 'tank_auth'),
            'font_path' => './' . $this->config->item('captcha_fonts_path', 'tank_auth'),
            'font_size' => $this->config->item('captcha_font_size', 'tank_auth'),
            'img_width' => $this->config->item('captcha_width', 'tank_auth'),
            'img_height' => $this->config->item('captcha_height', 'tank_auth'),
            'show_grid' => $this->config->item('captcha_grid', 'tank_auth'),
            'expiration' => $this->config->item('captcha_expire', 'tank_auth'),
                ));

        // Save captcha params in session
        $this->session->set_flashdata(array(
            'captcha_word' => $cap['word'],
            'captcha_time' => $cap['time'],
        ));

        return $cap['image'];
    }

    /**
     * Callback function. Check if CAPTCHA test is passed.
     *
     * @param	string
     * @return	bool
     */
    function _check_captcha($code) {
        $time = $this->session->flashdata('captcha_time');
        $word = $this->session->flashdata('captcha_word');

        list($usec, $sec) = explode(" ", microtime());
        $now = ((float) $usec + (float) $sec);

        if ($now - $time > $this->config->item('captcha_expire', 'tank_auth')) {
            $this->form_validation->set_message('_check_captcha', $this->lang->line('auth_captcha_expired'));
            return FALSE;
        } elseif (($this->config->item('captcha_case_sensitive', 'tank_auth') AND
                $code != $word) OR
                strtolower($code) != strtolower($word)) {
            $this->form_validation->set_message('_check_captcha', $this->lang->line('auth_incorrect_captcha'));
            return FALSE;
        }
        return TRUE;
    }

    /**
     * Create reCAPTCHA JS and non-JS HTML to verify user as a human
     *
     * @return	string
     */
    function _create_recaptcha() {
        $this->load->helper('recaptcha');

        // Add custom theme so we can get only image
        $options = "<script>var RecaptchaOptions = {theme: 'custom', custom_theme_widget: 'recaptcha_widget'};</script>\n";

        // Get reCAPTCHA JS and non-JS HTML
        $html = recaptcha_get_html($this->config->item('recaptcha_public_key', 'tank_auth'));

        return $options . $html;
    }

    /**
     * Callback function. Check if reCAPTCHA test is passed.
     *
     * @return	bool
     */
    function _check_recaptcha() {
        $this->load->helper('recaptcha');

        $resp = recaptcha_check_answer($this->config->item('recaptcha_private_key', 'tank_auth'), $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);

        if (!$resp->is_valid) {
            $this->form_validation->set_message('_check_recaptcha', $this->lang->line('auth_incorrect_captcha'));
            return FALSE;
        }
        return TRUE;
    }

}

/* End of file auth.php */
/* Location: ./application/controllers/auth.php */